/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.event;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.Condition;
import com.sinodata.bsm.center.bean.EventCorrelationLinkBean;
import com.sinodata.bsm.center.bean.EventCorrelationPolicyBean;
import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.bean.ResTypeBean;
import com.sinodata.bsm.center.bean.TreeData;
import com.sinodata.bsm.center.cache.EventCorrelationLinkCache;
import com.sinodata.bsm.center.cache.EventCorrelationPolicyCache;
import com.sinodata.bsm.center.cache.EventTypeCache;
import com.sinodata.bsm.center.cache.RelationTypeCache;
import com.sinodata.bsm.center.cache.ResCache;
import com.sinodata.bsm.center.engine.event.correlation.EventCorrelationManager;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.event.EventCorrelationPolicyService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.vo.EventCorrelationLink;
import com.sinodata.bsm.common.vo.EventCorrelationPolicy;
import com.sinodata.bsm.common.vo.EventType;
import com.sinodata.bsm.common.vo.RelationType;
import com.sinodata.bsm.common.vo.Res;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author dongyushi
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-6-14 上午10:08:11          dongyushi        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class EventCorrelationAction extends BaseAction<EventCorrelationPolicy> {

    /**
     * 
     */
    private static final long serialVersionUID = 3727596093509517194L;
    @Autowired
    private EventCorrelationPolicyService eventCorrelationPolicyService;
    @Autowired
    private ResCache resCache;
    @Autowired
    private EventTypeCache eventTypeCache;
    @Autowired
    private RelationTypeCache relationTypeCache;
    @Autowired
    private EventCorrelationPolicyCache eventCorrelationPolicyCache;
    @Autowired
    private EventCorrelationLinkCache eventCorrelationLinkCache;
    private Long id;
    private EventCorrelationPolicy entity;

    public String common() {
        //权限控制
        boolean sysManager = UserFunctionValidate.sysFunctionValidate(FunctionConstants.SYSTEM_MANAGER);
        Struts2Utils.setRequestAttribute("sysManager", sysManager);
        return "common";
    }

    public String add() {
        return "add";
    }

    public String addLink() {
        request.setAttribute("sNum", request.getParameter("sNum"));
        return "addlink";
    }

    public String addExpression() {
        String sNum = request.getParameter("sNum");
        List<String> list = new ArrayList<String>();
        if (sNum != null) {
            list = Arrays.asList(sNum.split(","));
        }
        request.setAttribute("sNumList", list);
        String extendConfig = request.getParameter("extendConfig");
        List<String> list2 = new ArrayList<String>();
        if (extendConfig != null && !extendConfig.equals("")) {
            extendConfig = StringUtils.replace(extendConfig, "$", "&");
            String[] exts = extendConfig.split("[||]");
            for (String str : exts) {
                if (str == null || str.equals("")) {
                    continue;
                }
                list2.add(str);
            }
        }
        request.setAttribute("extendConfig", list2);
        return "addexpression";
    }

    @Override
    public EventCorrelationPolicy getModel() {
        return entity;
    }

    @Override
    public String list() throws Exception {
        Page<EventCorrelationPolicyBean> page = new Page<EventCorrelationPolicyBean>();
        page.setPageNo(Integer.valueOf(request.getParameter("iDisplayStart")) / Integer.valueOf(request.getParameter("iDisplayLength")) + 1);
        page.setPageSize(Integer.valueOf(request.getParameter("iDisplayLength")));
        //条件查询
        String name = request.getParameter("name");
        Condition condition = new Condition();
        Map<String, String> map = new HashMap<String, String>();
        if (name != null && !name.equals("")) {
            map.put("name", "'" + name + "'");
        }
        condition.setWhere(map);
        Page<EventCorrelationPolicyBean> aaData = eventCorrelationPolicyService.findByPage(page, condition);
        JSONObject json = new JSONObject();
        json.element("iTotalRecords", page.getTotal());
        json.element("iTotalDisplayRecords", page.getTotal());
        JSONArray array = new JSONArray();
        //权限控制
        boolean sysManager = UserFunctionValidate.sysFunctionValidate(FunctionConstants.SYSTEM_MANAGER);
        for (EventCorrelationPolicyBean eventCorrelationPolicyBean : aaData.getRows()) {
            JSONObject obj = new JSONObject();
            if (sysManager) {
                if (eventCorrelationPolicyBean.getEventCorrelationPolicy().getStatus().equals("1")) {
                    obj.element("op", "<div style='width: 100px'>&nbsp;&nbsp;&nbsp;<a href='javascript:changeStatus(" + eventCorrelationPolicyBean.getEventCorrelationPolicy().getId() + ");'><img src='../style/default/bsm/images/stop.gif' title='停用'></a>&nbsp;<a href='javascript:update(" + eventCorrelationPolicyBean.getEventCorrelationPolicy().getId() + ");'><img src='../style/default/bsm/images/edit.gif' title='修改'></a>&nbsp;<a href='javascript:del(" + eventCorrelationPolicyBean.getEventCorrelationPolicy().getId() + ");'><img src='../style/default/bsm/images/delete.gif' title='删除'></a><div>");
                } else {
                    obj.element("op", "<div style='width: 100px'>&nbsp;&nbsp;&nbsp;<a href='javascript:changeStatus(" + eventCorrelationPolicyBean.getEventCorrelationPolicy().getId() + ");'><img src='../style/default/bsm/images/start.gif' title='启用'></a>&nbsp;<a href='javascript:update(" + eventCorrelationPolicyBean.getEventCorrelationPolicy().getId() + ");'><img src='../style/default/bsm/images/edit.gif' title='修改'></a>&nbsp;<a href='javascript:del(" + eventCorrelationPolicyBean.getEventCorrelationPolicy().getId() + ");'><img src='../style/default/bsm/images/delete.gif' title='删除'></a><div>");
                }
            }
            obj.element("name", "<a href='javascript:view(" + eventCorrelationPolicyBean.getEventCorrelationPolicy().getId() + ");'>" + eventCorrelationPolicyBean.getEventCorrelationPolicy().getName() + "</a>");
            obj.element("mainEventTypeName", eventCorrelationPolicyBean.getMainEventTypeName());
            obj.element("status", eventCorrelationPolicyBean.getEventCorrelationPolicy().getStatus().equals("1") ? "启用" : "停用");
            obj.element("memo", eventCorrelationPolicyBean.getEventCorrelationPolicy().getMemo() == null ? " " : eventCorrelationPolicyBean.getEventCorrelationPolicy().getMemo());
            obj.element("id", eventCorrelationPolicyBean.getEventCorrelationPolicy().getId());
            array.add(obj);
        }
        json.element("aaData", array);
        renderText(json.toString());
        return null;
    }

    public String eventTypeViewTree() {
        String resId = request.getParameter("resId");
        if (resId != null && !resId.equals("")) {
            Res res = resCache.get(Long.valueOf(resId));
            ResTypeBean resTypeBean = ResTypeBean.get(res.getResTypeId());
            List<EventType> listEventType = resTypeBean.eventType();
            //自定义事件类别
            List<EventType> list = eventTypeCache.findByResId(Long.valueOf(resId));
            List<EventType> listResult = new ArrayList<EventType>();
            if (listEventType != null) {
                listResult.addAll(listEventType);
            }
            if (list != null) {
                listResult.addAll(list);
            }
            JSONArray jsonArray = new JSONArray();
            for (EventType eventType : listResult) {
                TreeData treeData = new TreeData();
                treeData.setId("event" + String.valueOf(eventType.getId()));
                treeData.setName(eventType.getName());
                treeData.setIconSkin("eventtype");
                jsonArray.add(treeData);
            }
            Struts2Utils.renderText(jsonArray.toString());
        } else {
            //列出全部资源的资源类别及其事件类别
            List<TreeData> list = eventCorrelationPolicyService.getResTypeTreeData();
            JSONArray jsonArray = JSONArray.fromObject(list);
            Struts2Utils.renderText(jsonArray.toString());
        }
        return null;
    }

    public String relationTypeViewTree() {
        List<RelationType> listAll = relationTypeCache.getAll();
        //第一级关系
        Set<RelationType> set = new HashSet<RelationType>();
        for (RelationType relationType : listAll) {
            if (relationType.getParent() == null) {
                set.add(relationType);
            }
        }
        List<TreeData> list = getRelationTypeTreeData(set);
        JSONArray jsonArray = JSONArray.fromObject(list);
        Struts2Utils.renderText(jsonArray.toString());
        return null;
    }

    //遍历获取关系类型树
    private List<TreeData> getRelationTypeTreeData(Set<RelationType> set) {
        List<TreeData> listResult = new ArrayList<TreeData>();
        for (RelationType relationType : set) {
            TreeData treeData = new TreeData();
            treeData.setId(String.valueOf(relationType.getId()));
            treeData.setName(relationType.getName());

            List<RelationType> listAll = relationTypeCache.getAll();
            Set<RelationType> set1 = new HashSet<RelationType>();
            for (RelationType relationType1 : listAll) {
                if (relationType1.getParent() != null && relationType1.getParent().equals(relationType.getId())) {
                    set1.add(relationType1);
                }
            }
            treeData.setChildren(getRelationTypeTreeData(set1));
            listResult.add(treeData);
        }
        return listResult;
    }

    public String view() throws Exception {
        EventCorrelationPolicy eventCorrelationPolicy = eventCorrelationPolicyCache.get(Long.valueOf(request.getParameter("id")));
        EventCorrelationPolicyBean eventCorrelationPolicyBean = new EventCorrelationPolicyBean();
        eventCorrelationPolicyBean.setEventCorrelationPolicy(eventCorrelationPolicy);
        if (eventCorrelationPolicy.getResId() != null) {
            eventCorrelationPolicyBean.setMainResName(resCache.get(eventCorrelationPolicy.getResId()).getName());
        }
        eventCorrelationPolicyBean.setMainEventTypeName(eventTypeCache.get(eventCorrelationPolicy.getMainEventType()).getName());
        Struts2Utils.getRequest().setAttribute("eventCorrelationPolicyBean", eventCorrelationPolicyBean);
        List<EventCorrelationLinkBean> listResult = new ArrayList<EventCorrelationLinkBean>();
        List<EventCorrelationLink> list = eventCorrelationLinkCache.getAll();
        for (EventCorrelationLink eventCorrelationLink : list) {
            if (eventCorrelationLink.getEventCorrelationPolicyId().equals(eventCorrelationPolicy.getId())) {
                EventCorrelationLinkBean eventCorrelationLinkBean = new EventCorrelationLinkBean();
                eventCorrelationLinkBean.setEventCorrelationLink(eventCorrelationLink);
                if (eventCorrelationLink.getResId() != null) {
                    eventCorrelationLinkBean.setResName(resCache.get(eventCorrelationLink.getResId()).getName());
                }
                eventCorrelationLinkBean.setEventTypeLinkName(eventTypeCache.get(eventCorrelationLink.getEventTypeLinkId()).getName());
                eventCorrelationLinkBean.setResRelationName(relationTypeCache.get(eventCorrelationLink.getResRelation()).getName());
                listResult.add(eventCorrelationLinkBean);
            }
        }
        Struts2Utils.getRequest().setAttribute("eventCorrelationLinkList", listResult);
        Struts2Utils.getRequest().setAttribute("status", eventCorrelationPolicy.getStatus().equals("0") ? "停用" : "启用");
        return "view";
    }

    @Override
    public String input() throws Exception {
        EventCorrelationPolicy eventCorrelationPolicy = eventCorrelationPolicyCache.get(Long.valueOf(request.getParameter("id")));
        EventCorrelationPolicyBean eventCorrelationPolicyBean = new EventCorrelationPolicyBean();
        eventCorrelationPolicyBean.setEventCorrelationPolicy(eventCorrelationPolicy);
        if (eventCorrelationPolicy.getResId() != null) {
            eventCorrelationPolicyBean.setMainResName(resCache.get(eventCorrelationPolicy.getResId()).getName());
        }
        eventCorrelationPolicyBean.setMainEventTypeName(eventTypeCache.get(eventCorrelationPolicy.getMainEventType()).getName());
        Struts2Utils.getRequest().setAttribute("eventCorrelationPolicyBean", eventCorrelationPolicyBean);
        List<EventCorrelationLinkBean> listResult = new ArrayList<EventCorrelationLinkBean>();
        List<EventCorrelationLink> list = eventCorrelationLinkCache.getByPolicy(eventCorrelationPolicy.getId());
        int sNum = 0;
        for (EventCorrelationLink eventCorrelationLink : list) {
            EventCorrelationLinkBean eventCorrelationLinkBean = new EventCorrelationLinkBean();
            eventCorrelationLinkBean.setEventCorrelationLink(eventCorrelationLink);
            if (eventCorrelationLink.getResId() != null) {
                eventCorrelationLinkBean.setResName(resCache.get(eventCorrelationLink.getResId()).getName());
            }
            eventCorrelationLinkBean.setsNum(sNum++);
            eventCorrelationLinkBean.setEventTypeLinkName(eventTypeCache.get(eventCorrelationLink.getEventTypeLinkId()).getName());
            eventCorrelationLinkBean.setResRelationName(relationTypeCache.get(eventCorrelationLink.getResRelation()).getName());
            listResult.add(eventCorrelationLinkBean);
        }
        StringBuffer data = new StringBuffer();
        int num = listResult.size();
        if (listResult.size() != 0) {
            for (EventCorrelationLinkBean eventCorrelationLinkBean : listResult) {
                data.append(eventCorrelationLinkBean.getEventCorrelationLink().getSerialNumber()).append("|");
                data.append(eventCorrelationLinkBean.getEventCorrelationLink().getResId()).append("|");
                data.append(eventCorrelationLinkBean.getEventCorrelationLink().getEventTypeLinkId()).append("|");
                data.append(eventCorrelationLinkBean.getEventCorrelationLink().getResRelation()).append(",");
            }
            data.delete(data.lastIndexOf(","), data.length());
        }
        Struts2Utils.getRequest().setAttribute("data", data);
        Struts2Utils.getRequest().setAttribute("sNum", num + 1);
        Struts2Utils.getRequest().setAttribute("eventCorrelationLinkList", listResult);
        return "update";
    }

    @Override
    public String save() throws Exception {
        //从事件数据
        String data = request.getParameter("data");
        List<EventCorrelationLink> list = new ArrayList<EventCorrelationLink>();
        if (data != null) {
            String[] array = data.split(",");
            for (int i = 0; i < array.length; i++) {
                if (array[i] != null && !array[i].equals("")) {
                    String[] array1 = array[i].split("[|]");
                    EventCorrelationLink e = new EventCorrelationLink();
                    if (array1[0] != null && !array1[0].equals("")) {
                        e.setSerialNumber(String.valueOf(array1[0]));
                    }
                    if (array1[1] != null && !array1[1].equals("") && !array1[1].equals("null")) {
                        e.setResId(Long.valueOf(array1[1]));
                    }
                    if (array1[2] != null && !array1[2].equals("")) {
                        e.setEventTypeLinkId(Long.valueOf(array1[2]));
                    }
                    if (array1[3] != null && !array1[3].equals("")) {
                        e.setResRelation(Long.valueOf(array1[3]));
                    }
                    list.add(e);
                }
            }
        }
        if (entity.getId() != null) {
            if (eventCorrelationPolicyCache.get(entity.getId()) != null) {
                Long id1 = eventCorrelationPolicyService.update(entity, list);
                eventCorrelationPolicyCache.put(entity.getId(), entity);
                //先删除和主事件关联的从事件
                for (EventCorrelationLink e : eventCorrelationLinkCache.getAll()) {
                    if (e.getEventCorrelationPolicyId().equals(id1)) {
                        eventCorrelationLinkCache.remove(e.getId());
                    }
                }
                //再新增从事件
                for (EventCorrelationLink e : list) {
                    e.setEventCorrelationPolicyId(id1);
                    eventCorrelationLinkCache.put(e.getId(), e);
                }
            } else {
                renderText("false");
                return null;
            }
        } else {
            //新增时默认启用
            entity.setStatus("1");
            Long id1 = eventCorrelationPolicyService.add(entity, list);
            eventCorrelationPolicyCache.put(entity.getId(), entity);
            for (EventCorrelationLink e : list) {
                e.setEventCorrelationPolicyId(id1);
                eventCorrelationLinkCache.put(e.getId(), e);
            }
        }
        //EventCorrelationManager.getInstance().changeECPStatus();//直接获取活动的事件相关性规则进行更新
        renderText("true");
        return null;
    }

    @Override
    public String delete() throws Exception {
        if (eventCorrelationPolicyCache.get(id) != null) {
            List<EventCorrelationLink> list = eventCorrelationPolicyService.delete(id);

            eventCorrelationPolicyCache.remove(id);
            for (EventCorrelationLink eventCorrelationLink : list) {
                if (eventCorrelationLink.getEventCorrelationPolicyId().equals(id)) {
                    eventCorrelationLinkCache.remove(eventCorrelationLink.getId());
                }
            }
            EventCorrelationManager.getInstance().changeECPStatus();//直接获取活动的事件相关性规则进行更新
            renderText("true");
        } else {
            renderText("false");
        }
        return null;
    }

    public String checkDeleted() {
        JSONObject ob = new JSONObject();
        if (eventCorrelationPolicyCache.get(id) == null) {
            ob.element("flag", false);
        } else {
            ob.element("flag", true);
        }
        Struts2Utils.renderJson(ob.toString());
        return null;
    }

    public String changeStatus() throws Exception {
        if (eventCorrelationPolicyCache.get(id) != null) {
            EventCorrelationPolicy eventCorrelationPolicy = eventCorrelationPolicyService.changeStatus(id);
            eventCorrelationPolicyCache.put(eventCorrelationPolicy.getId(), eventCorrelationPolicy);
            EventCorrelationManager.getInstance().changeECPStatus();//直接获取活动的事件相关性规则进行更新
            renderText("true");
        } else {
            renderText("false");
        }
        return null;
    }

    public String checkName() throws Exception {
        String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
        name = name.replace(" ", "----");
        name = java.net.URLDecoder.decode(name, "UTF-8");
        name = name.replace("----", "+");
        String oldName = "";
        if (request.getParameter("oldName") != null && !request.getParameter("oldName").equals("")) {
            oldName = new String(request.getParameter("oldName").getBytes("ISO-8859-1"), "UTF-8");
            oldName = oldName.replace(" ", "----");
            oldName = java.net.URLDecoder.decode(oldName, "UTF-8");
            oldName = oldName.replace("----", "+");
        }
        if (!name.equals(oldName)) {
            if (eventCorrelationPolicyService.checkName(name)) {
                renderText("true");
            } else {
                renderText("false");
            }
        } else {
            renderText("true");
        }
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {
        if (id != null) {
            entity = eventCorrelationPolicyService.get(id);
            if (entity == null) {
                entity = new EventCorrelationPolicy();
            }
        } else {
            entity = new EventCorrelationPolicy();
        }
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}
